package other;

import main.Resource;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

/**
 * 鼠标移动动画
 *
 * @author fdh
 */
public class MouseMoveAnim extends JPanel {
    private JPanel panel;
    public Thread anim;
    public Point pos = new Point(0, 0);

    public MouseMoveAnim(JFrame frame) {
        panel = this;
        panel.setSize(Resource.Config.mouseMoveImgSize);
        panel.setOpaque(false);
        MyImgIcon img = new MyImgIcon(Resource.Config.mouseMoveImg, MyImgIcon.ShowType.Fill, panel);
        panel.add(new JLabel(img));
        frame.getRootPane().addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseDragged(MouseEvent e) {

            }

            @Override
            public void mouseMoved(MouseEvent e) {
                pos.setLocation(e.getX(), e.getY());
            }
        });
        startAnim();
    }

    public void startAnim() {
        anim = new Thread(() -> {
            while (!Thread.interrupted()) {
                try {
                    Thread.sleep(Resource.Config.mouseMoveUpdateTime);
                    if (pos != null) {
                        panel.setLocation(pos.x + Resource.Config.mouseMoveImgOffset.width,
                                pos.y + Resource.Config.mouseMoveImgOffset.height);
                    }
                } catch (InterruptedException e) {
                    System.out.println("鼠标移动动画线程中断");
                } catch (Exception e) {
                    System.out.println("鼠标移动动画线程故障");
                }
            }
        });
        anim.start();
    }

    public void destroy() {
        anim.interrupt();
    }
}
